package sf.dsl.example;

import sf.database.dialect.DBDialect;
import sf.database.jdbc.sql.SQLContext;
import sf.database.jdbc.sql.SQLParameter;
import sf.tools.StringUtils;

import java.util.List;

/**
 * 查询的 table，
 * 实例1：用于构建 select * from (select ...) 中的第二个 select
 * 实例2：用于构建 left join (select ...) 中的 select
 */
public class WrapperSimpleTable extends SimpleTable {

    private Example query;

    public WrapperSimpleTable(Example query) {
        super();
        this.query = query;
    }

    public Example getQuery() {
        return query;
    }

    public void setQuery(Example query) {
        this.query = query;
    }

    @Override
    public void toSql(StringBuilder sb, List<SQLParameter> list, DBDialect dialect) {
        toNoAliasSql(sb, list, dialect);
        if (StringUtils.isNotBlank(tableAlias)) {
            String alias = tableAlias;
            if (dialect != null) {
                alias = dialect.wrapKeyword(tableAlias);
            }
            sb.append(" as ").append(alias);
        }
    }

    @Override
    public void toNoAliasSql(StringBuilder sb, List<SQLParameter> list, DBDialect dialect) {
        query.dialect = dialect;
        SQLContext sqlContext = ExampleSQL.getSelectSQLContext(query, null, SelectOpt.all, true);
        String sql = sqlContext.getSql();
        if (list != null) {
            list.addAll(sqlContext.getParas());
        }
        sb.append('(').append(sql).append(')');
    }
}
